package work.soho.proxy.aliyun.parts;

import com.aliyuncs.AcsRequest;
import com.aliyuncs.AcsResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import work.soho.proxy.PartsConfigure;
import work.soho.proxy.ProxyApplication;

public class BasePart implements IConfig {
    private String accessKeyId = "";
    private String accessSecret = "";

    /**
     * 配置信息
     */
    protected PartsConfigure configure = null;

    /**
     * 实例所属的地域ID
     */
    protected String regionId = "cn-hongkong";

    /**
     * 配置配置信息
     *
     * @param config
     */
    public void setConfig(PartsConfigure config) {
        this.configure = config;
    }

    /**
     * 需要填充账号的AccessKey ID，以及账号的Access Key Secret
     */
    private IAcsClient initClient() {
        IClientProfile profile = DefaultProfile.getProfile(configure.getRegionId(), configure.getAccessKeyId(), configure.getAccessSecret());
        return new DefaultAcsClient(profile);
    }

    /**
     * 调用OpenAPI的方法，这里进行了错误处理
     *
     * @param request AcsRequest, Open API的请求
     * @param <T> AcsResponse 请求所对应返回值
     * @return 返回OpenAPI的调用结果，如果调用失败，则会返回null
     */
    protected  <T extends AcsResponse> T  callOpenApi(AcsRequest<T> request) {
        IAcsClient client = initClient();
        try {
            T response = client.getAcsResponse(request, false, 0);
           // logInfo(String.format("Success. OpenAPI Action: %s call successfully.", request.getActionName()));
            return response;
        } catch (ServerException e) {
            logInfo(String.format("Fail. Something with your connection with Aliyun go incorrect. ErrorCode: %s",
                    e.getErrCode()));
        } catch (ClientException e) {
            logInfo(String.format("Fail. Business error. ErrorCode: %s, RequestId: %s",
                    e.getErrCode(), e.getRequestId()));
            e.printStackTrace();
        } catch (Exception e) {
            logInfo(e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    private static void logInfo(String message) {
        System.out.println(message);
      //  ProxyApplication.infoBox(message, "运行错误信息");
    }
}
